package db

import (
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
	"strings"
	"time"
)

var DB *gorm.DB

func GetDB() *gorm.DB {
	return DB
}

func Init() *gorm.DB {
	driver := strings.ToLower(viper.GetString("db.driver"))
	var db *gorm.DB
	var err error
	switch driver {
	case "mysql":
		db, err = getMysql()
	default:
		db, err = getMysql()
	}
	if err != nil {
		panic(err)
	}
	DB = db

	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	DB.DB().SetMaxIdleConns(10)

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	DB.DB().SetMaxOpenConns(100)

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	DB.DB().SetConnMaxLifetime(time.Hour)

	// 去掉表名称后面的s
	DB.SingularTable(true)

	// 是否开启日志
	DB.LogMode(viper.GetBool("db.log"))
	return DB
}

func getMysql() (*gorm.DB, error) {
	dbname := viper.GetString("db.name")
	host := viper.GetString("db.host")
	port := viper.GetString("db.port")
	user := viper.GetString("db.user")
	password := viper.GetString("db.password")
	return MysqlConnection(host, port, user, password, dbname)
}
